package cn.ecnu.common.utils;

import cn.ecnu.common.constant.Constant;
import cn.ecnu.common.exception.RRXException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Date;


@ConfigurationProperties(prefix = "psy.jwt")
@Component
@Slf4j
public class JwtUtil {

    private long expire = 1; // 十分钟的过期时间
    private String secret = "12456"; // 加密盐值
    private String header = "PSY"; // 头
    private static final String TOKEN_PREFIX = "psy:token:user:";

    @Autowired
    StringRedisTemplate redisTemplate;


    /**
     * 生成JWT Token
     * @param userId
     * @return
     */
    public String sign(Integer userId) {
        try {
            Date now = new Date();
            String token = Jwts.builder()
                    .setIssuedAt(now)
                    .setSubject(String.valueOf(userId))
                    .signWith(SignatureAlgorithm.HS512, secret)
                    .compact(); // 进行用户签名加密

            redisTemplate.opsForValue().set(TOKEN_PREFIX + userId, token, Duration.ofMinutes(expire)); // 在redis中进行设置这个token, 只允许一个用户处于登录
            log.info(token);
            return token;
        } catch (Exception e) {
            return null;
        }
    }

    public Integer getUserId(String token) {
        Integer userId;
        try {
            userId = Integer.parseInt(Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody()
                    .getSubject()); // 首先获取userId
        } catch (Exception e) {
            throw new RRXException(Constant.AUTH_ERROR.getMsg(), Constant.AUTH_ERROR.getCode());
        }
        String tokenInRedis = redisTemplate.opsForValue().get(TOKEN_PREFIX + userId); // 对比token
        if (!StringUtils.equals(token, tokenInRedis)) throw new RRXException(Constant.AUTH_ERROR.getMsg(), Constant.AUTH_ERROR.getCode());
        return userId;
    }



    public long getExpire() {
        return expire;
    }

    public void setExpire(long expire) {
        this.expire = expire;
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }
}
